import React from 'react'

class classTest extends React.Component {
  constructor(props) {
    super(props)
    this.state = {n: 0}
  }
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    return nextState.n !== this.state.n;
  }

  onClick = () => {
    this.setState((state,props)=>{
      console.log('props')
      console.log(props)
      return ({n:state.n+1}) //返回一个对象的化最好用（）包起来
    })
    this.setState((state)=>{
      return ({n:state.n-1}) //返回一个对象的化最好用（）包起来
    })
    //函数设置就可以执行两次+1，如果直接是对象（onClick2）的话，就只有一次+1
  }
  onClick2 = ()=>{
    this.setState({n:this.state.n+1},()=>{
      this.setState({n:this.state.n+1})
    })
    //this.setState的第二个参数是设置state成功之后的回调
  }
  render() {
    return (
      <Son fromFather={this.state.n} onClick={this.onClick}/>
    )
  }
}

class Son extends React.Component {
  constructor(props) {
    super(props)
  }
  componentWillReceiveProps(nextProps, nextContext) {
    console.log('旧的props')
    console.log(this.props)
    console.log('新的props')
    console.log(nextProps)
  }

  render() {
    console.log('执行了render')
    return (
      <div className='son'>
        <button onClick={this.props.onClick}>+1,-1</button>
        <div>{this.props.fromFather}</div>
      </div>
    )
  }
}

export default classTest